﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Xml;
using DaInterFace;
using DaInterFace.SYN;

namespace DaFunction.SYN
{
    [ServiceContract()]
    public interface ISYNApi
    {
        [OperationContract]
        String CodeGet(String userKey);
        [OperationContract]
        String CodeSet(String parameter);
        [OperationContract]
        String MCode(String parameter);
        [OperationContract]
        String MBase(String parameter);
        [OperationContract]
        String MFile(byte[] data, string filename);
        [OperationContract]
        String updateTransferFlag(String userKey, string id);
        [OperationContract]
        String updateSettleFlag(String userKey, String id, String flags, String tableName, String fieldName, String baseNo);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class SYNApi : ISYNApi
    {
        public static ISYN DaSYN;

        private SYNRight CheckRight(String key)
        {
            return new SYNRight();
        }

        public String CodeSet(String parameters)
        {
            CodeResult result = new CodeResult();
            DateTime curtime = DateTime.Now;
            SerialType st = SerialType.Json;
            try
            {
                SYNParameter mp = (SYNParameter)DaSYN.Serial.Deserialize(st, typeof(SYNParameter), parameters);
                String code = mp.CodeName;

                SYNRight user = CheckRight(mp.User);

                if (user != null)
                {
                    try
                    {
                        Assembly ass = Assembly.Load("E01");  //加载dll文件
                        Type tp = ass.GetType("E01." + code);  //获取类名，必须 命名空间+类名
                        ISYNChildSet tempSet = (ISYNChildSet)Activator.CreateInstance(tp);  //建立实例
                        tempSet.Code(DaSYN, result, user, st, mp.Parameters);

                        DaSYN.Message(MessageType.Note, String.Format("E01.{0}：{1}", code, result.Message), (DateTime.Now - curtime).TotalMilliseconds);
                    }
                    catch (Exception ex)
                    {
                        result.Result = EnumResult.None;
                        result.Message = String.Format("Code代码错误，请联系管理人员，接收到的代码：{0},错误:{1}", mp.CodeName , ex.Message);
                        DaSYN.Message(MessageType.Error, String.Format("E01.{0}：{1}", code, result.Message), (DateTime.Now - curtime).TotalMilliseconds);
                    }
                }
                else
                {
                    result.Result = EnumResult.None;
                    result.Message = "无效的认证信息。";
                }

            }
            catch (Exception ex)
            {
                result.Result = EnumResult.None;
                result.Message = ex.Message;
            }

            return DaSYN.Serial.Serializer(st, typeof(CodeResult), result);
        }

        public String CodeGet(String userKey)
        {
            CodeResult result = new CodeResult();
            SerialType st = SerialType.Json;
            DateTime curtime = DateTime.Now;
            String id = "";

            try
            {
                SYNRight user = CheckRight(userKey);

                if (user != null)
                {
                    Recordset rs = DaSYN.Data.ExeBase(
                        " declare @id int " +
                        " SELECT TOP 1 @id = A.FID FROM KEW_SYNData A LEFT JOIN KEW_DataBase B ON A.FBase=B.FID  " +
                        " WHERE FCheckBox=0 and FInteger < 20 ORDER BY convert(int,(FInteger1 + FInteger/2)),NewID() asc " +
                        " update KEW_SYNData set FInteger = FInteger + 1 where FID = @id " +
                        " SELECT TOP 1 A.FID,A.FText1 BillId,A.FText TypeId,A.FText2 UpdateType,A.FCheckBox1 SetFlag, A.FTime NewTime," +
                        " B.FNumber BaseNo FROM KEW_SYNData A LEFT JOIN KEW_DataBase B ON A.FBase=B.FID where a.FID = @id ");
                    if (rs.Enable)
                    {
                        if (rs.Data.Tables[0].Rows.Count == 1)
                        {
                            DataRow row = rs.Data.Tables[0].Rows[0];
                            String code = row["TypeId"].ToString();
                            id = row["FID"].ToString();

                            switch (row["UpdateType"].ToString())
                            {
                                case "I": result.Result = EnumResult.Insert; break;
                                case "U": result.Result = EnumResult.Update; break;
                            }

                            try
                            {
                                Assembly ass = Assembly.Load("E02");  //加载dll文件
                                Type tp = ass.GetType("E02." + code);  //获取类名，必须 命名空间+类名
                                ISYNChildGet tempGet = (ISYNChildGet)Activator.CreateInstance(tp);  //建立实例
                                tempGet.Code(DaSYN, ref result, user, st, row["BaseNo"].ToString(), row["BillId"].ToString());

                                DaSYN.Message(MessageType.Note, String.Format("E02.{0}：{1}", code, result.Message), (DateTime.Now - curtime).TotalMilliseconds);
                            }
                            catch (Exception ex)
                            {
                                result.Result = EnumResult.None;
                                result.Message = "Code代码错误，请联系管理人员：E02." + code + ex.Message;
                                DaSYN.Message(MessageType.Error, String.Format("E02.{0}：{1}", code, result.Message), (DateTime.Now - curtime).TotalMilliseconds);
                            }
                        }
                        else
                        {
                            result.Result = EnumResult.None;
                        }
                    }
                    else
                    {
                        result.Result = EnumResult.None;
                        result.Message = rs.Message;
                        DaSYN.Message(MessageType.Error, String.Format("同步失败:{0}", rs.Message), (DateTime.Now - curtime).TotalMilliseconds);
                    }
                }
                else
                {
                    result.Result = EnumResult.None;
                    result.Message = "无效的认证信息。";
                }
            }
            catch (Exception ex)
            {
                result.Result = EnumResult.None;
                result.Message = ex.Message;
            }
            result.recordID = id;
            return DaSYN.Serial.Serializer(st, typeof(CodeResult), result);
        }

        public String updateTransferFlag(String userKey, string id)
        {
            CodeResult result = new CodeResult();
            SerialType st = SerialType.Json;
            DateTime curtime = DateTime.Now;
            try
            {
                SYNRight user = CheckRight(userKey);
                if (user != null)
                {
                    string sql = "select * from KEW_SYNData where FID = " + id + "   delete from KEW_SYNData where FID = " + id;
                    Recordset rs = DaSYN.Data.ExeBase(sql);
                    if (rs.Enable)
                    {
                        if (rs.Data.Tables[0].Rows.Count == 1)
                        {
                            DataRow row = rs.Data.Tables[0].Rows[0];
                            sql = "update " + row["FText3"] + " set synchro = 1 where fid = " + row["FText1"]
                                    + "  select synchro from " + row["FText3"] + " where fid = " + row["FText1"];
                            rs = DaSYN.Data.ExeProcedure(row["BaseNo"].ToString(), sql);
                            if (rs.Data.Tables[0].Rows.Count == 1)
                            {
                                result.Result = EnumResult.Update;
                            }
                            else
                            {
                                result.Result = EnumResult.None;
                            }
                        }
                        else
                        {
                            result.Result = EnumResult.None;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Result = EnumResult.None;
                result.Message = ex.Message;
            }

            return DaSYN.Serial.Serializer(st, typeof(CodeResult), result);

        }


        public String updateSettleFlag(String userKey, String id, String flag, String tableName, String fieldName, String baseNo)
        {
            CodeResult result = new CodeResult();
            SerialType st = SerialType.Json;
            DateTime curtime = DateTime.Now;
            try
            {
                SYNRight user = CheckRight(userKey);
                if (user != null)
                {
                    String sql = "update " + tableName + " set " + fieldName + " = " + flag + " where FID in (" + id + ") select 1";
                    Recordset rs = DaSYN.Data.ExeProcedure(baseNo, sql);
                    if (rs.Data.Tables[0].Rows.Count == 1)
                    {
                        result.Result = EnumResult.Update;
                    }
                    else
                    {
                        result.Result = EnumResult.None;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Result = EnumResult.None;
                result.Message = ex.Message;
            }

            return DaSYN.Serial.Serializer(st, typeof(CodeResult), result);

        }

        public String MCode(String parameters)
        {
            CodeResult result = new CodeResult();
            DateTime curtime = DateTime.Now;
            SerialType st = SerialType.Json;
            try
            {
                SYNParameter mp = (SYNParameter)DaSYN.Serial.Deserialize(st, typeof(SYNParameter), parameters);
                String code = mp.CodeName;
                SYNRight user = CheckRight(mp.User);

                if (user != null)
                {
                    try
                    {

                        Assembly ass = Assembly.Load("E90");  //加载dll文件
                        Type tp = ass.GetType("E90." + code);  //获取类名，必须 命名空间+类名
                        ISYNChildSet tempSet = (ISYNChildSet)Activator.CreateInstance(tp);  //建立实例
                        tempSet.Code(DaSYN, result, user, st, mp.Parameters);

                        DaSYN.Message(MessageType.Note, String.Format("E01.{0}：{1}", code, result.Message), (DateTime.Now - curtime).TotalMilliseconds);
                    }
                    catch (Exception ex)
                    {
                        result.Result = EnumResult.None;
                        result.Message = String.Format("Code代码错误，请联系管理人员，接收到的代码：{0},错误:{1}", mp.CodeName, ex.Message);
                        DaSYN.Message(MessageType.Error, String.Format("E01.{0}：{1}", code, result.Message), (DateTime.Now - curtime).TotalMilliseconds);
                    }
                }
                else
                {
                    result.Result = EnumResult.None;
                    result.Message = "无效的认证信息。";
                }

            }
            catch (Exception ex)
            {
                result.Result = EnumResult.None;
                result.Message = ex.Message;
            }

            return DaSYN.Serial.Serializer(st, typeof(CodeResult), result);
        }

        public String MBase(String parameters)
        {
            Recordset rs = new Recordset();
            try
            {
                String dp = AES.Decrypt(parameters, "96518762965187629651876296518762");
                ManagerParameters mp = (ManagerParameters)XML.Deserialize(typeof(ManagerParameters), dp);
                RightServer.Service right = new RightServer.Service();

                if (right.KEW_IsAllowSql("0632PassWordO1!", Fingerprint.GetFingerprint(), ""))
                {
                    if (mp.Base == "")
                    {
                        rs = DaSYN.Data.ExeBase(mp.Content);
                    }
                    else
                    {
                        rs = DaSYN.Data.ExeProcedure(mp.Base, mp.Content);
                    }
                }
                else
                {
                    rs.Enable = false;
                    rs.Message = "未获得授权";
                }
            }
            catch (Exception ex)
            {
                rs.Enable = false;
                rs.Message = ex.Message;
            }
            return AES.Encrypt(XML.Serializer(typeof(Recordset), rs), "96518762965187629651876296518762"); ;
        }

        public String MFile(byte[] data, string filename)
        {
            try
            {
                RightServer.Service right = new RightServer.Service();
                if (right.KEW_IsAllowSql("0632PassWordO1!", Fingerprint.GetFingerprint(), ""))
                {
                    FileStream fs = File.Create(AppValues.GetPath() + filename);
                    fs.Write(data, 0, data.Length);
                    fs.Close();
                    return "上传成功";
                }
                else
                {
                    return "没有获得授权";
                }
            }
            catch(Exception ex)
            {
                return "上传失败:" + ex.Message;
            }
        }
    }

    public class ManagerParameters
    {
        public String Base;
        public String Content;
    }
}
